package avicit.bdp.dds.server.utils;

import avicit.bdp.dds.common.utils.OSUtils;
import org.junit.Assert;
import org.junit.Test;
import org.jvnet.winp.WinProcess;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class KillWindowsPorcessTest {
    @Test(timeout = 60*1000)
    public void windowsProcessKillerTest() throws Exception {
        if (OSUtils.isWindows() ) {
            int pid = exec(TestProc.class); // start a process for test
            WinProcess process = new WinProcess(pid) ;

            Assert.assertTrue(process.isRunning()); ;

            // kill the process
            ProcessUtils.killWindowsPorcess(pid);

            Assert.assertFalse(process.isRunning()) ;
        }
    }

    private static int exec(Class klass) throws IOException,
            InterruptedException {
        String javaHome = System.getProperty("java.home");
        String javaBin = javaHome +
                File.separator + "bin" +
                File.separator + "java";
        String classpath = System.getProperty("java.class.path");
        String className = klass.getName();

        List<String> command = new LinkedList<String>();
        command.add(javaBin);
        command.add("-cp");
        command.add(classpath);
        command.add(className);

        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.inheritIO().start();
        WinProcess proc = new WinProcess( process ) ;
        return proc.getPid() ;
    }

    public static class TestProc {
        public static void main(String[] args) {
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                   System.out.println("Shut down.");
                }
            }));

            for (;;) {
                System.out.println("running....") ;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
